<template>
	<el-scrollbar class="w-full h-full px-6">
		<departmentCheckbox v-if="!focusChart" @doSelected="changeSelectedDepartment"></departmentCheckbox>

		<div class="flex flex-col w-full py-6 space-y-10">
			<div class="flex-1" v-for="name in [
				'FanXiangRenShu',
				'DianShi',
				//'ZaiXianFengZhi',
				'KaiTongPaiDanGuiDang',
				'TouSuPaiDanGuiDang',
			]" :key="name">
				<div class="flex-wrap hidden md:flex-nowrap md:justify-between">
					<el-radio-group class="mb-2" v-if="name === 'FanXiangRenShu'" v-model="showModel" @change="showModelChange">
						<el-radio-button value="all" label="all">所有</el-radio-button>
						<el-radio-button v-if="includesDepartment1" value="region" label="region">只展示区域</el-radio-button>
						<el-radio-button v-if="includesDepartment2" value="grid" label="grid">只展示网格</el-radio-button>
					</el-radio-group>
					<datePicker v-if="name === 'FanXiangRenShu'" @change="changeFXDate" :allDates="fanXiangDates" />
				</div>
				<el-button type="primary" @click="exportNLData(name)"
					v-if="name === 'KaiTongPaiDanGuiDang' || name === 'TouSuPaiDanGuiDang'">导出当前数据</el-button>
				<myChart bodyClass="w-full h-96" :name="name" :getDomRef="getDomRef" title="" :focusChart="focusChart"
					@toggle-focus="(e) => (focusChart = e)" />
			</div>
		</div>
	</el-scrollbar>
</template>

<script setup>
import * as echarts from 'echarts';
import { nlData } from '@/components/options/FanXiang/nlData';
import { ref, reactive, onMounted } from 'vue';
import myChart from '@/common/components/myChart.vue';
import departmentCheckbox from '@/common/components/departmentCheckbox.vue';
import datePicker from '@/common/components/datePicker.vue';
import department from '@/common/getDepartment';
import formatter from '@/common/formatter';
const { department1, department2 } = department;

const getOptionFn = () => import('@/components/options/getOption');
import { watchResize, watchFocus } from './logic';
import solarlunar from 'solarlunar';
const { dataPool } = defineProps(['dataPool']),
	{ dataPool1, dataPool2 } = dataPool;

const focusChart = ref(''),
	domChart = reactive({}),
	showModel = ref('all'),
	includesDepartment1 = ref(true),
	includesDepartment2 = ref(false);

const charts = window.allCharts['FanXiang'];

const getDomRef = (name) => (el) => (domChart[name] = ref(el));

const selectedDepartment = ref([['茂南', '电白', '高州', '化州', '信宜'], []]),
	mergeDepartment = ref([]),
	changeSelectedDepartment = (e) => {
		selectedDepartment.value = e;
		mergeDepartment.value = department.mergeSelection(selectedDepartment.value);
		includesDepartment1.value =
			department1.some((value) => e.flat().includes(value)) || !e.flat().length;
		includesDepartment2.value = department2
			.flat()
			.some((value) => e.flat().includes(value));
		Object.keys(charts).forEach((name) => {
			const option = charts[name].option;
			if (option.getChartData) {
				const newData = option.getChartData(
					[dataPool1, dataPool2],
					e,
					mergeDepartment.value,
					selectedDate.value
				);
				sourceCache[name] = newData;
				charts[name].setOption(option);
			}
		});
	};

const fanXiangDates = ref([
	...new Set(dataPool2.fanxiangrenshu.map((i) => i.date)),
]);
const selectedDate = ref(Math.max(...fanXiangDates.value));

const changeFXDate = (days) => {
	selectedDate.value = days;
	const name = 'FanXiangRenShu';
	const chartInstance = charts[name];

	const option = chartInstance.option;
	const newData = option.getChartData(
		[dataPool1, dataPool2],
		selectedDepartment.value,
		mergeDepartment.value,
		selectedDate.value
	);
	sourceCache[name] = newData;
	charts[name].setOption(option);

	option.dataset.source = newData;
	chartInstance.setOption(option);
};

const sourceCache = {};
const showModelChange = (v) => {
	const chartInstance = charts['FanXiangRenShu'];
	const option = chartInstance.option;
	const newSource = sourceCache['FanXiangRenShu'].filter((d, index) => {
		if (index === 0 || v === 'all') return true;
		if (v === 'region') {
			return department1.includes(d[0]);
		}
		if (v === 'grid') {
			return department2.flat().includes(d[0]);
		}
	});

	option.dataset.source = newSource;
	chartInstance.setOption(option);
};

onMounted(async () => {

	// 统计 农历返乡人数
	var o = dataPool.dataPool2.fanxiangrenshu.reduce((p, c) => {
		p[c.date] ? p[c.date].push(c) : (p[c.date] = [c]);
		return p;
	}, {})
	dataPool2[`nlPrevFXRS`] = [];
	dataPool2[`nlPrevZhanBi`] = [];
	dataPool2[`nlThisFXRS`] = [];
	dataPool2[`nlThisZhanBi`] = [];

	NLObj.prevYearDays.map(d => {
		let rsObj = { "日期": d }, zbObj = { "日期": d };
		if (o[d]) {
			o[d].forEach(c => {
				rsObj[c.grid] = c.renshu;
				zbObj[c.grid] = c.zhanbi;
			});
		}
		o[d] && (rsObj['全市'] = Object.values(rsObj).reduce((p, c) => p + c, 0));

		dataPool2[`nlPrevFXRS`].push(rsObj);
		dataPool2[`nlPrevZhanBi`].push(zbObj);
	});

	NLObj.thisYearDays.map(d => {
		let rsObj = { "日期": d }, zbObj = { "日期": d };
		if (o[d]) {
			o[d].forEach(c => {
				rsObj[c.grid] = c.renshu;
				zbObj[c.grid] = c.zhanbi;
			});
		}
		o[d] && (rsObj['全市'] = Object.values(rsObj).reduce((p, c) => p + c, 0));

		dataPool2[`nlThisFXRS`].push(rsObj);
		dataPool2[`nlThisZhanBi`].push(zbObj);
	});

	Object.keys(domChart).forEach(async (chart) => {
		charts[chart] = echarts.init(domChart[chart]);
		const getOption = (await getOptionFn()).default;
		const option = await getOption('FanXiang', chart);
		if (option.getChartData) {
			const newData = option.getChartData([dataPool1, dataPool2]);
			sourceCache[chart] = newData;
		}
		charts[chart].setOption(option);
		charts[chart].option = option;
	});

	watchFocus(focusChart, charts);
	watchResize(charts);
});

const exportNLData = (name) => {
	// const thisYearKuanDai = dataPool2[`nl${NLObj.thisYear}kuandai`]
	// const prevYearKuanDai = dataPool2[`nl${NLObj.prevYear}kuandai`]
	// const [tyKD, pyKD] = [thisYearKuanDai, prevYearKuanDai].map(arr => {
	// 	return arr.map(i => {
	// 		const [y, m, d] = formatter.excelDate(i.date).split('/');
	// 		const nl = solarlunar.solar2lunar(y, m, d);
	// 		return {
	// 			"农历": nl.monthCn + nl.dayCn,
	// 			...i
	// 		}
	// 	})
	// });

	// var workbook = XLSX.utils.book_new();
	// [
	// 	{ name: `nl${NLObj.thisYear}kuandai`, data: tyKD },
	// 	{ name: `nl${NLObj.prevYear}kuandai`, data: pyKD },
	// ].forEach(({ name, data }) => {
	// 	const worksheet = XLSX.utils.json_to_sheet(data);
	// 	XLSX.utils.book_append_sheet(workbook, worksheet, name);

	// })
	// XLSX.writeFile(workbook, "农历宽带数据" + (new Date().getTime()) + ".xlsx", { compression: true });
	let tDaysObj = {};
	NLObj.thisYearDays.map(date => {
		let commonDate = formatter.excelDate(date, 'YYYY/MM/DD')
		let [y, m, d] = commonDate.split('/')
		let nlDate = solarlunar.solar2lunar(y, m, d)
		let nlStr = nlDate.monthCn + nlDate.dayCn;
		tDaysObj[nlStr] = commonDate;
	})
	let pDaysObj = {};
	NLObj.prevYearDays.map(date => {
		let commonDate = formatter.excelDate(date, 'YYYY/MM/DD')
		let [y, m, d] = commonDate.split('/')
		let nlDate = solarlunar.solar2lunar(y, m, d);
		let nlStr = nlDate.monthCn + nlDate.dayCn;
		pDaysObj[nlStr] = commonDate;
	})

	let data = allCharts.FanXiang[name].option.dataset.source;
	data = data.map((item, index) => {
		if (name === 'KaiTongPaiDanGuiDang') {
			const [nlDate, pxp, txp, pgd, tgd, pzt, tzt, phdl, thdl, pztgdb, tztgdb] = item;
			let pSolarDate = index === 0 ? NLObj.prevYear + '新历日期' : (pDaysObj[nlDate] || '')
			let tSolarDate = index === 0 ? NLObj.thisYear + '新历日期' : (tDaysObj[nlDate] || '')
			return [
				nlDate,
				pSolarDate,
				pxp, pgd, pzt, phdl, pztgdb,
				tSolarDate,
				txp, tgd, tzt, thdl, tztgdb,
			]
		}
		if (name === 'TouSuPaiDanGuiDang') {
			const [nlDate, pxp, txp, pgd, tgd, pzt, tzt] = item;
			let pSolarDate = index === 0 ? NLObj.prevYear + '新历日期' : (pDaysObj[nlDate] || '')
			let tSolarDate = index === 0 ? NLObj.thisYear + '新历日期' : (tDaysObj[nlDate] || '')
			return [
				nlDate,
				pSolarDate,
				pxp, pgd, pzt,
				tSolarDate,
				txp, tgd, tzt,
			]
		}
	})
	var workbook = XLSX.utils.book_new();
	const worksheet = XLSX.utils.aoa_to_sheet(data);
	XLSX.utils.book_append_sheet(workbook, worksheet, name);
	XLSX.writeFile(workbook, name + '-' + (new Date().getTime()) + ".xlsx", { compression: true });

}
</script>

<style scoped>
.el-card {
	flex: 1;
}
</style>
